#pragma once
#ifndef _UI_H
#define _UI_H

#include "Renderer.h"
#include <vector>
#include <functional>
#include <string>

//坐标尺寸结构体
struct UIRect {
    int x,y;//远原点顶点坐标
    int w,h;
};

//UI元素抽象基类
class UIElement {
protected:
    UIRect rect;//元素位置、大小
    bool isVisible;//是否可见
public:
    UIElement(const UIRect& r) : rect(r), isVisible(true) {};
    virtual ~UIElement() = default;
    virtual void draw(Renderer* renderer) = 0;//绘制元素
    //处理鼠标点击
    virtual bool handleClick(int mouseX, int mouseY);
    void setVisible(bool visible) {this->isVisible = visible;}
    bool IsVisible()const { return this->isVisible; }
};

//按钮
class Button : public UIElement {
private:
    std::string text;//文字
    std::function<void(std::string)> onClick;//点击回调
public:
    Button(const UIRect& r,const std::string& txt,std::function<void(std::string)> callback)
        : UIElement(r), text(txt), onClick(std::move(callback)) {}
    void draw(Renderer* renderer) override;
    bool handleClick(int mouseX,int mouseY) override;
};

//文本标签
class TextLabel : public UIElement {
private:
    std::string text;
    int color;
public:
    TextLabel(const UIRect& r,const std::string& txt,int clr) : UIElement(r) , text(txt), color(clr) {}
    void draw(Renderer* renderer) override;
    bool handleClick(int mouseX, int mouseY) override
    { return false; }//不处理标签，则返回false
    void setText(const std::string& txt) {this->text = txt;}//更新文本

};

//UI管理器
class UIManager {
private:
    std::vector<UIElement*> elements;
    Renderer* renderer;
public:
    UIManager(Renderer* r) : renderer(r) {}
    ~UIManager() {
        for (auto elem : elements) delete elem;
    }
    void addElement(UIElement* elem) { elements.push_back(elem); }
    void drawAll()const {
        for (auto elem : elements) {
            if (elem->IsVisible()) elem->draw(renderer);
        }
    }
    //分发鼠标点击事件给所有元素
    void dispatchClick(int mouseX, int mouseY)const {
        for (auto elem : elements) {
            if (elem->IsVisible() && elem->handleClick(mouseX, mouseY)) {
                break;//此处逻辑为点击只触发一个元素
            }
        }
    }
};
#endif
